//
//  ACChangeAuthorController.m
//  MonitoringSystem
//
//  Created by FreedomCoco on 16/7/26.
//  Copyright © 2016年 Interlube. All rights reserved.
//

#import "ACChangeAuthorController.h"
#import <IQKeyboardManager.h>
#import "NetRequestClass.h"
#import "UtilToolsClass.h"
@interface ACChangeAuthorController ()<UITextFieldDelegate,UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UIButton *submitBtn;
@property (weak, nonatomic) IBOutlet UILabel *txtAuthorGuid;
@property (weak, nonatomic) IBOutlet UITextField *txtPhone;
- (IBAction)commitCallBack:(id)sender;
@end

@implementation ACChangeAuthorController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"管理权限转移", nil);
    self.txtAuthorGuid.text = NSLocalizedString(@"AUTHOR_GUID", nil);
    [self.submitBtn setTitle:NSLocalizedString(@"提交",nil) forState:UIControlStateNormal];
    [self.txtPhone setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
     self.txtPhone.placeholder = NSLocalizedString(@"请输入对方的手机号码", nil);
    [self.txtPhone setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.txtPhone addTarget:self action:@selector(LVCtextLengthMethod:) forControlEvents:UIControlEventEditingChanged];
    
    // 设置返回按钮
    UIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back@3x"] style:UIBarButtonItemStylePlain target:self action:@selector(backItemClick)];
    self.navigationItem.leftBarButtonItem = backItem;
    self.navigationItem.hidesBackButton = YES;
    
    UINavigationBar *navigationBar = self.navigationController.navigationBar;
    [navigationBar setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [navigationBar setShadowImage:[UIImage createImageWithColor:[UIColor colorWithRed:108/255.0 green:112/255.0 blue:112/255.0 alpha:0.5]]];
   
    UITapGestureRecognizer * tapGuest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchViewForDownKeyBoard)];
    [self.view addGestureRecognizer:tapGuest];
}


- (void) touchViewForDownKeyBoard{
    [self.view endEditing:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}


- (void)backItemClick{
   [self.navigationController popViewControllerAnimated:YES];
}


- (void)LVCtextLengthMethod:(UITextField *)textField{
    
    if (self.txtPhone == textField) {
        if (textField.text.length >= 11) {
            textField.text = [textField.text substringToIndex:11];
        }
    }
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}

#pragma mark 检验用户ID
- (void)requestVerifyUserPhone{
    NSString * showStr = @"";
    if ([UtilToolsClass judgeLocalLanguage] == 1) {
        showStr = [NSString stringWithFormat:@"将设备编号为:%@的权限转移给%@用户？",self.imei,self.txtPhone.text];;
    }else{
       showStr = [NSString stringWithFormat:@"User %@ will be the new administrator of Pump %@？",self.txtPhone.text,self.imei];
    }
    
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"提示",nil) message:showStr delegate:self cancelButtonTitle:NSLocalizedString(@"取消",nil) otherButtonTitles:NSLocalizedString(@"确定",nil), nil];
    [alertView show];
}



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [[UtilToolsClass getUtilTools] addDoLoading];
        __weak typeof(self)weakSelf = self;
        [NetRequestClass requestWithUrlForTranistAuthor:self andUrl:[REQUESTHEADER stringByAppendingString:@"deviceList/moveAdmin.asp"] andParam:@{@"userId":self.txtPhone.text,@"i_imei":self.imei} success:^(NSInteger result) {
            [[UtilToolsClass getUtilTools] removeDoLoading];
            [weakSelf requestSuccessCallBack:result];
         } failure:^(NSString *failure) {
            [[UtilToolsClass getUtilTools] removeDoLoading];
            [UtilToolsClass addDisapperAlert:@"" withMessage:failure];
        }];
    }
}


/**
 *  请求成功回调
 *
 */
- (void)requestSuccessCallBack:(NSInteger )result{
    if (result == 1) {
        [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"输入的用户不存在,权限转移失败", nil)];
    }else if(!result){
        if (self.isDeviceInfoEnter) {
//             [UtilToolsClass addDisapperAlert:@"" withMessage:@"转移管理员成功"];
             [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            // 发送解绑请求
            __weak typeof(self) weakSelf = self;
            [NetRequestClass requestWithUrlForUnBindingDevice:nil andUrl:[REQUESTHEADER stringByAppendingString:@"deviceList/deviceRemoveBinding.asp"] andParam:@{@"i_imei":self.imei,@"bindingCount":@(self.bindings)} success:^(NSInteger result) {
                if (!result ) {
                    // 成功
                    [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"转移权限成功,设备已解绑",nil)];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                    });
                }else{
                    // 失败
                    [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"失败", nil)];
                }
            } failure:^(NSString *failure) {
                [UtilToolsClass addDisapperAlert:@"" withMessage:failure];
            }];

        }
        
       }else if (result == 2){
        [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"输入的用户没有绑定此设备,权限转移失败", nil)];
   }else if (result == 3){
       [UtilToolsClass addDisapperAlert:@"" withMessage:NSLocalizedString(@"权限不能转移给自己",nil)];
   }

}

- (IBAction)commitCallBack:(id)sender {
    [self requestVerifyUserPhone];
}
@end
